package com.view.cn.mvprxjava.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.view.cn.mvprxjava.R;
import com.view.cn.mvprxjava.utils.ToastUtils;

import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observable;
import rx.functions.Action1;

/**
 * Created by Zengxiaoping on 2016/9/26.
 */

public class RxjavaTimerFragment extends BaseFragment {

	public static final String TAG = RxjavaTimerFragment.class.getSimpleName();

	@Bind(R.id.tv_lambda1)
	TextView mTvLambda1;
	@Bind(R.id.tv_lambda2)
	TextView mTvLambda2;

	private Handler mHandler = new Handler();

	public static RxjavaTimerFragment newInstance() {
		RxjavaTimerFragment fragment = new RxjavaTimerFragment();
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_rxjava_timer, container, false);

		initView(view);
		initEvent();

		return view;
	}

	private void initView(View view) {
		ButterKnife.bind(this, view);
	}

	private void initEvent() {
		mTvLambda1.setOnClickListener(v -> {
			//可能引起内存泄露,持有外部activity的引用，当antivity被销毁时，。一般推荐的都是使用static的handler，并且结合软引用，控制handler的消息处理。
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					ToastUtils.getInstance().showToast(getActivity().getApplicationContext(), "点击了handler");
				}
			},4000);
		});
		mTvLambda2.setOnClickListener(v -> {
			Observable.timer(4, TimeUnit.SECONDS).subscribe(new Action1<Long>() {
				@Override
				public void call(Long aLong) {
					ToastUtils.getInstance().showToast(getActivity().getApplicationContext(), "点击了Rxjava的timer");
				}
			});
		});
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		ButterKnife.unbind(this);
	}
}
